import React,{useEffect} from 'react'
import {RouteComponentProps,useParams,useLocation} from 'react-router-dom'
import {Typography,Spin,Pagination} from 'antd'
import {useSelector,useDispatch} from 'react-redux'
import {RootState} from "../../redux/store/store";
import {searchProductList} from "../../redux/Search/slice";
import ProductList from "../../components/ProductList/ProductList";
import MyHeaderFunc from "../../components/MyHeader/MyHeaderFunc";
import './search.css'
interface MatchParams{
    pagenumber:string|undefined,
    pagesize:string|undefined,
    keyword:string|undefined
}
export const Search:React.FC<RouteComponentProps<MatchParams> >=(props)=> {
    const dispatch = useDispatch();
    const location=useLocation();
    var {pagenumber,pagesize,keyword} = useParams<MatchParams>();
    const isloading = useSelector((state: RootState) => state.productlist.isloading)
    const error = useSelector((state: RootState) => state.productlist.error)
    const productlist = useSelector((state: RootState) => state.productlist.productlist)
    const pagination=useSelector((state:RootState)=>state.productlist.pagination)
    const myonChange = (page:number) => {
        dispatch(searchProductList({pagenumber:page,pagesize:pagination.pageSize,keyword:keyword}));
    };
    useEffect(() => {
        dispatch(searchProductList({pagenumber:pagenumber===undefined?'1':pagenumber,pagesize:pagesize===undefined?'10':pagesize,keyword}))
    }, [location])
    if (isloading) {
        return (<Spin style={{width: "100%", height: "100vh"}}></Spin>)
    } else if (error) {
        return (<Typography.Title type="danger">网络出错</Typography.Title>)
    }else if(pagination===null){
        return (<Typography.Title type="danger">无{keyword}的搜索结果</Typography.Title>)
    }
    return (
        <div>
            <MyHeaderFunc></MyHeaderFunc>
            <ProductList productlist={productlist}></ProductList>
            <div className="page">
                <Pagination current={pagination.currentPage} onChange={myonChange} defaultCurrent={1} total={pagination.totalCount} />
                <h2>共{pagination.totalPages}页，共{pagination.totalCount}条搜索结果</h2>
            </div>
        </div>
    )
}